package com.github.llyb120.driver.qiuya;

import com.github.llyb120.driver.qiuya.request.ReqAggregate;
import com.github.llyb120.driver.qiuya.request.ReqCount;
import com.github.llyb120.driver.qiuya.request.ReqDelete;
import com.github.llyb120.driver.qiuya.request.ReqUpdate;
import com.github.llyb120.json.Obj;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;

import javax.swing.text.html.Option;
import java.util.List;
import java.util.Map;

import static com.github.llyb120.driver.qiuya.request.ReqBase.*;
import static com.github.llyb120.json.Json.*;

public class Collection {
    public Database database;
    public String name;

    public Collection(Database database, String name){
        this.database = database;
        this.name = name;
    }

    public Query find(){
        return find(null);
    }

    public Query find(Map $match){
        Query query = new Query(this);
        if ($match != null) {
            query.$match = $match;
        }
        return query;
    }

    public Query aggregate(List $aggregate){
        Query query = new Query(this);
        query.built = a($expand, $aggregate);
        return query;
    }

    public long count(){
        return count(null);
    }

    public long count(Map $match){
        Obj obj = database.client.send(COMMAND_COUNT, new ReqCount(database.name, name, $match));
        Long l = obj.l("data");
        if (l == null) {
            return 0;
        }
        return l;
    }

    public void updateOne(Map $match, Map action){
        updateOne($match, action, new UpdateOptions());
    }

    public void updateOne(Map $match, Map action, UpdateOptions options){
        database.client.send(COMMAND_UPDATE, new ReqUpdate(database.name, name, $match, action, options.isUpsert()));
    }

    public void deleteOne(Map $match){
        database.client.send(COMMAND_DELETE, new ReqDelete(database.name, name, $match));
    }
}
